# compiler
CXX ?= g++

# debug or release
DEBUG ?= 1
ifeq ($(DEBUG), 1)
	CXXFLAGS += -g
else
	CXXFLAGS += -O2
endif

CXXFLAGS += -std=c++17

OUTPUT_DIR := bin
EXEC_TARGET := $(OUTPUT_DIR)/server

LIB_NAME := zhserver
LIB_TARGET := $(OUTPUT_DIR)/lib$(LIB_NAME).a

# 默认目标：生成静态库和可执行程序
all: $(LIB_TARGET) $(EXEC_TARGET)

THIRD_PARTY_BUILD := build_3rdparty
CREATE_OUTPUT_DIR := create_output_dir

LOG_LIB_DIR := 3rdparty/spdlog
LOG_LIB_NAME := spdlog

SOURCE_ROOT_DIR := src

CXXFLAGS += -L$(LOG_LIB_DIR)
CXXFLAGS += -l$(LOG_LIB_NAME)
CXXFLAGS += -lpthread
CXXFLAGS += -I$(LOG_LIB_DIR)/include

CXXFLAGS += -I$(SOURCE_ROOT_DIR)

SOURCES := main.cpp ./$(SOURCE_ROOT_DIR)/web_server.cpp \
		$(wildcard $(SOURCE_ROOT_DIR)/logger/*.cpp) \
		$(wildcard $(SOURCE_ROOT_DIR)/epoll/*.cpp) \
		$(wildcard $(SOURCE_ROOT_DIR)/timer/*.cpp) \
		$(wildcard $(SOURCE_ROOT_DIR)/http/*.cpp)\
		$(wildcard $(SOURCE_ROOT_DIR)/buffer/*.cpp)\
		$(wildcard $(SOURCE_ROOT_DIR)/thread_pool/*.cpp)


# 创建输出目录
$(CREATE_OUTPUT_DIR):
	@echo create bin
	@mkdir -p $(OUTPUT_DIR)


# 生成目标文件列表
OBJ_FILES = $(SOURCES:.cpp=.o)

# 生成静态库，排除 main.cpp
$(LIB_TARGET): $(filter-out main.cpp, $(OBJ_FILES)) | $(CREATE_OUTPUT_DIR)
	@echo "Building $(LIB_TARGET)..."
	ar rcs $@ $^
	@echo "$(LIB_TARGET) built successfully."

# 生成可执行程序
$(EXEC_TARGET): $(OBJ_FILES) | $(THIRD_PARTY_BUILD)
	@echo "Building $(EXEC_TARGET)..."
	$(CXX) -o $@ $^ $(CXXFLAGS)
	@echo "$(EXEC_TARGET) built successfully."
	

# 生成目标文件
$(OBJ_FILES): %.o : %.cpp
	@echo "Compiling $<..."
	$(CXX) $(CXXFLAGS) -c $< -o $@

$(THIRD_PARTY_BUILD):
	@echo "Tip: Please make sure you have executed build_3rdparty.sh before."

clean:
	@echo "Cleaning..."
	rm $(OBJ_FILES) $(LIB_TARGET) $(EXEC_TARGET)
	@echo "Clean completed."
